package cn.jdy.plugins.wap;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.socket.TextMessage;

import redis.clients.jedis.Jedis;
import cn.jdy.authority.entity.Organ;
import cn.jdy.authority.service.OrganService;
import cn.jdy.common.ctrl.BaseCtrl;
import cn.jdy.framework.db.redis.JedisService;
import cn.jdy.framework.log.BaseLog;
import cn.jdy.framework.util.DateUtil;
import cn.jdy.framework.util.StringUtil;
import cn.jdy.platform.service.ConfService;
import cn.jdy.plugins.entity.Advertising;
import cn.jdy.plugins.entity.Chat;
import cn.jdy.plugins.entity.CheckLive;
import cn.jdy.plugins.entity.EvaluationProject;
import cn.jdy.plugins.entity.ExamOptions;
import cn.jdy.plugins.entity.ExamQuestions;
import cn.jdy.plugins.entity.Label;
import cn.jdy.plugins.entity.Line;
import cn.jdy.plugins.entity.Live;
import cn.jdy.plugins.entity.PptImg;
import cn.jdy.plugins.entity.RedPacket;
import cn.jdy.plugins.entity.WatchUser;
import cn.jdy.plugins.service.AdvertisingService;
import cn.jdy.plugins.service.ChatService;
import cn.jdy.plugins.service.CheckLiveService;
import cn.jdy.plugins.service.EvaluationProjectService;
import cn.jdy.plugins.service.ExamOptionsService;
import cn.jdy.plugins.service.ExamQuestionsService;
import cn.jdy.plugins.service.LabelService;
import cn.jdy.plugins.service.LineService;
import cn.jdy.plugins.service.LiveService;
import cn.jdy.plugins.service.PptImgService;
import cn.jdy.plugins.service.RedPacketService;
import cn.jdy.plugins.service.RelatedVideoService;
import cn.jdy.plugins.service.SecretKeyCetService;
import cn.jdy.plugins.service.WatchUserService;
import cn.jdy.plugins.websocket.WebsocketEndPoint;

/**
 * @title ceshi
 * @author ningqian
 * @since 2017-3-23
 */

@Controller
@RequestMapping("/chat")
public class ChatCtrl extends BaseCtrl {
	@Autowired
	private OrganService organService;
	@Autowired
	private LineService lineService;
	@Autowired
	private WatchUserService watchUserService;
	@Autowired
	private ChatService chatService;
	@Autowired
	private LiveService liveService;
	@Autowired
	private ConfService confService;
	@Autowired
	private LabelService labelService;
	@Autowired
	private AdvertisingService advertisingService;
	@Autowired
	private RelatedVideoService relatedVideoService;
	@Autowired
	private EvaluationProjectService evaluationProjectService;
	@Autowired
	private ExamOptionsService examOptionsService;

	@Autowired
	private ExamQuestionsService examQuestionsService;
	@Autowired
	private RedPacketService redPacketService;
	@Autowired
	private SecretKeyCetService secretKeyCetService;
	
	@Autowired
	private CheckLiveService checkLiveService;
	@Autowired
	private PptImgService pptImgService;
	private static String searchTime; // 查询时间

	private static Long liveId;

	/**
	 * 查看历史交流
	 * 
	 * @param rpSendId
	 * @return
	 */
	@RequestMapping("getChatHistory")
	@ResponseBody
	public Map<String, Object> getChatHistory(Long liveId, int pageNo,
			int pageSize, int sign) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		Long count = 0L;
		List<Chat> list = new ArrayList<Chat>();
		if (sign == 1) { // 查询历史记录
			String firstTime = DateUtil.getCurrentDate(DateUtil._DEFAULT2);
			searchTime = firstTime;
			list = chatService
					.queryHistory(liveId, firstTime, pageNo, pageSize);
			count = chatService.count(liveId, firstTime);
		} else if (sign == 2) { // 下一页
			list = chatService.queryHistory(liveId, searchTime, pageNo,
					pageSize);
			count = chatService.count(liveId, searchTime);
		}
		jsonMap.put("datalist", list);
		jsonMap.put("iTotalDisplayRecords", count);
		return jsonMap;
	}

	/**
	 * 加载ppt
	 * 
	 * @param rpSendId
	 * @return
	 */
	@RequestMapping("getppt")
	@ResponseBody
	public Map<String, Object> getppt(Long pptListid, int pageNo, int pageSize) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		Long count = 0L;
		List<PptImg> list = new ArrayList<PptImg>();
		DetachedCriteria dc = DetachedCriteria.forClass(PptImg.class);
		if (!StringUtil.isNullOrEmpty(pptListid)) {
			dc.add(Restrictions.eq("pptListid", pptListid));
		}
		dc.addOrder(Order.asc("sortTop"));
		dc.addOrder(Order.asc("sortLeft"));
		list = pptImgService.find(dc,pageNo, pageSize);
		count = pptImgService.count(dc);
		jsonMap.put("datalist", list);
		jsonMap.put("iTotalDisplayRecords", count);
		return jsonMap;
	}

	@RequestMapping("/edit/{id}")
	public ModelAndView edit(@PathVariable Long id) {
		liveId = id;
		ModelAndView mv = new ModelAndView();
		Map<String, Object> watchUser = new HashMap<String, Object>();
		// session.setAttribute(Constants.SESSION_USERNAME,
		// chat.getUserNickName());
		// session.setAttribute(Constants.SESSION_USERId, chat.getUserOpenId());
		watchUser.put("liveId", liveId);
		watchUser.put("appid", "wx003d8b600a48f618");
		watchUser.put("openid", "o1hlOtz9UjwYjdx3fAJnKRZFJLHU");
		watchUser.put("nickname", "M宁");
		watchUser
				.put("headimgurl",
						"http://wx.qlogo.cn/mmopen/POSU1ryY3vmXTHfJaZSoh4ibVwuy59jT3ej8BicfqhDl29aQue9d1FMU3nqhx1DemmPCeeanFo7K90OmtS8bteQsnYDCyVZFVK/0");
		watchUser.put("sex", "1");
		watchUser.put("mchid", "1296239001");
		watchUser.put("apikey", "11111111111111111111111111111111");

		session.setAttribute("watchUser", watchUser);
		Jedis jedis = new Jedis("127.0.0.1",6379);
		jedis.set("pt","2");
		System.out.println(jedis.get("pt")+"...............l");
		String attention = "0";
		String subscribe = "0";

		// 进入该直播间是否需要关注公众号 0 是 1 否
		// if(attention.equals("0")){
		// //如果已关注可直接进入三秒广告
		// if(subscribe.equals("1")){
		// //跳转到3秒广告界面
		// mv.setViewName("redirect:/chat/toIndex/");
		// }else{
		// //未关注引导用户关注官方公众号-跳转二维码关注页
		// mv.setViewName("redirect:/chat/guanzhu");
		// }
		// }else{
		// 跳转到3秒广告界面
		// mv.setViewName("redirect:/chat/toIndex/");
		// };

		mv.setViewName("redirect:/chat/toIndex/");
		return mv;
	}
	

	@SuppressWarnings({ "static-access", "unchecked" })
	@RequestMapping("/toIndex/")
	public ModelAndView toIndex(Label sp) {
		ModelAndView mv = new ModelAndView(super.t + "/index.jsp");
		BaseLog.e(this.getClass(), "当前直播id:" + liveId);
		Map<String, Object> watchUser = (Map<String, Object>) session
				.getAttribute("watchUser");
		if (null != watchUser && 0 < watchUser.size()) {
			Live live = liveService.find(liveId);
			mv.addObject("data", liveService.find(liveId));
			List<Map<String, String>>  belist=	labelService.querySiteMap(liveId);
			mv.addObject("labeldata", belist);
	
		
		
			
			List<Map<String, Object>> blist=labelService.queryLiveMap(liveId);
			for (int i = 0; i < blist.size(); i++) {
				 long labelid=((BigInteger) blist.get(i).get("labelid")).longValue();
				if(9889==labelid){
					mv.addObject("addata2", advertisingService.find("liveId", liveId,
							"advertisingType", "2"));// 交流广告
				}
				if(9890==labelid){
					mv.addObject("addata1", advertisingService.find("liveId", liveId,
							"advertisingType", "1"));// 合作广告
				}
				if(9904==labelid){
					DetachedCriteria dc = DetachedCriteria.forClass(Advertising.class);
				   // dc.add(Restrictions.eq("liveId", liveId));
				   // dc.add(Restrictions.eq("advertisingType", 3));
				   // advertisingService.find(dc, 0, 5); 
				 /*   advertisingService.find("liveId", liveId,
							"advertisingType", "3")*/
					
					mv.addObject("gzata1",advertisingService.find("liveId", liveId,
							"advertisingType", "3"));// 合作广告2
				}
			}
			if(live.getIspay()!=null&&live.getIspay().equals("1")){
				mv.addObject("sumzf", redPacketService.find("liveId", liveId,
						"userOpenId", watchUser.get("openid")+"","sendStatus","1","rpType","3").size());// 判断是否交钱
			}else if(live.getIspay()!=null&&live.getIspay().equals("2")){
				mv.addObject("ismiyao", secretKeyCetService.find("liveId", liveId,
						"userOpenId", watchUser.get("openid")+"","isStatus","1").size());// 判断秘钥正确
			}else if(live.getIspay()!=null&&live.getIspay().equals("3")){
				List<CheckLive> list= checkLiveService.find("liveId", liveId,
							"userOpenId", watchUser.get("openid")+"");
				if(list.size()>0){
					mv.addObject("isshenhe", list.get(0).getSendStatus());// 当前审核状态
				}else{
					mv.addObject("isshenhe", "4");// 当前审核状态

				}
				
			}
	
			/* for (int i = 0; i < blist.size(); i++) {
				//
				   long labelid=((BigInteger) blist.get(i).get("labelid")).longValue();;
				if(9903==labelid){  //判断是否有投票标签开始
					 	mv.addObject("isTpcs", examQuestionsService.isEvaluationRecord(liveId,watchUser.get("openid")+""));//查询是否投票
						EvaluationProject  ep=evaluationProjectService.findOne("liveId",liveId); //题头
						mv.addObject("ep", ep);// 题头
						if(ep!=null&&ep.getId()!=null){
							DetachedCriteria dc = DetachedCriteria.forClass(ExamQuestions.class);
						    dc.add(Restrictions.eq("projectId",ep.getId()));
							dc.addOrder(Order.asc("sort"));
							List<ExamQuestions> eqslist=examQuestionsService.find(dc);//题目
							for (int j = 0; j < eqslist.size(); j++) {
								ExamQuestions qe=eqslist.get(j);
								DetachedCriteria dcc = DetachedCriteria.forClass(ExamOptions.class);
								dcc.add(Restrictions.eq( "questionId",qe.getId()));
								dcc.addOrder(Order.asc("sort"));
								qe.setEqlist(examOptionsService.find(dcc));//选项
								
							}
							mv.addObject("eqslist", eqslist);
						}
					
				//ExamOptionsService
				 } //判断是否有投票标签结束
				
			} */
			String s = live.getCurrentStatus();
			String liveids = "";
			if (s != null && s != "") {
				liveids = s.substring(0, s.length() - 1);
			} else {
				liveids = "0";
			}
			mv.addObject("videodata", liveService.querySiteMap(liveids));
		} else {
			mv.setViewName("redirect:/chat/edit/" + liveId);
		}
		return mv;
	}

	@RequestMapping("/IndexS")
	public ModelAndView IndexS() {
		ModelAndView mv = new ModelAndView("/sendMessage.jsp");
		return mv;
	}

	@RequestMapping("/guanzhu")
	public ModelAndView guanzhu() {
		ModelAndView mv = new ModelAndView("/guanzhu.jsp");

		return mv;
	}

	public void getLO() {
		StringBuffer urls = request.getRequestURL();
		String str = urls.toString().split(":")[1];
		String url = str.substring(2, str.length());
		System.err.println(url);

	}

	public static void main(String[] args) {
		ChatCtrl v = new ChatCtrl();
		v.getLO();
	}
	/**
	 * 查看历史交流
	 * 
	 * @param rpSendId
	 * @return
	 */
	@RequestMapping("getToupaoHistory")
	public ModelAndView getToupaoHistory(Long liveId, String openid) {
		ModelAndView mv = new ModelAndView("/toupiao/tplist.jsp");
		Map<String, Object> watchUser = (Map<String, Object>) session
				.getAttribute("watchUser");
		mv.addObject("isTpcs", examQuestionsService.isEvaluationRecord(liveId,watchUser.get("openid")+""));//查询是否投票
		EvaluationProject  ep=evaluationProjectService.findOne("liveId",liveId); //题头
		mv.addObject("ep", ep);// 题头
		if(ep!=null&&ep.getId()!=null){
			DetachedCriteria dc = DetachedCriteria.forClass(ExamQuestions.class);
		    dc.add(Restrictions.eq("projectId",ep.getId()));
			dc.addOrder(Order.asc("sort"));
			List<ExamQuestions> eqslist=examQuestionsService.find(dc);//题目
			for (int j = 0; j < eqslist.size(); j++) {
				ExamQuestions qe=eqslist.get(j);
				DetachedCriteria dcc = DetachedCriteria.forClass(ExamOptions.class);
				dcc.add(Restrictions.eq( "questionId",qe.getId()));
				dcc.addOrder(Order.asc("sort"));
				qe.setEqlist(examOptionsService.find(dcc));//选项
				
			}
			mv.addObject("eqslist", eqslist);
		}
		return mv;
		}
	/**
	 * 添加留言信息
	 * 
	 * @param mgs
	 * @return
	 */
	@RequestMapping("addChat")
	@ResponseBody
	public Map<String, Object> addChat(String msg,@RequestParam("liveId") Long liveId,@RequestParam("userOpenId") String userOpenId) {
	Map<String, Object> jsonMap = new HashMap<String, Object>();{
			try {
				 String chatType = "1";  //消息类别1-文字，2-图片 3-红包消息
					 RedPacket red = redPacketService.findOne("orderNo",msg);
					 if(null != red){  //能查到红包 则为红包消息
						
						 
						 if(red.getRpType().equals("4")){
							 chatType = "4";//打赏信息
							 msg = red.getTotal() + ";" + red.getWishMsg();
							 BaseLog.e(this.getClass(), "处理客户端发来的消息......+"+msg);
							 System.out.println(msg);
						 }else{
							 chatType = "3";
							 msg = msg + ";" + red.getWishMsg();
						 }
				
					 }else{
						 if(msg.startsWith("/upload/confPic")){
							 chatType = "2";
						 }
					 }
					 BaseLog.e(this.getClass(), "处理客户端发来的消息......");
					
				
						Map<String, Object> user= (Map<String, Object>) session.getAttribute("watchUser");
						
				//		System.out.println(user.get("openid").toString()+"。。。。。");
						//屏蔽脏字
				    	String reg = "[艹|日|靠|槽|逼|草|婊|淫|骚]";
						String msg2 = msg.replaceAll(reg, "*");
						
						Chat chat = new Chat();
						WatchUser user2 = watchUserService.findOne("userOpenId",userOpenId);
				    	chat.setLiveId(liveId);
				    	chat.setUserOpenId(user2.getUserOpenId());
				    	chat.setUserNickName(user2.getUserNickName());
				    	chat.setUserHeadImg(user2.getUserHeadImg());
				    	chat.setUserSex(user2.getUserSex());
				    	chat.setChatType(chatType);
				    	chat.setChatContent(msg2);
				    	chat.setStatus("0");
				    	String createTime = DateUtil.getCurrentDate(DateUtil._DEFAULT2);
				    	chat.setCreateTime(createTime);
				    	chatService.save(chat);
				    	
				 
			jsonMap.put("statusCode", "200");
			} catch(Exception e) {
				jsonMap.put("statusCode", "400");
				BaseLog.e(getClass(), "异常！", e);
			}
	}
	return jsonMap;
	}
	/**
	 * 重新添加session 
	 * @param 
	 * @return
	 */
	@RequestMapping("saveSession") 
	@ResponseBody
    public Map<String,String> saveSession(@RequestParam("liveId") Long liveId,@RequestParam("userOpenId") String userOpenId) {
		Map<String,String> map = new HashMap<String,String>();
		String result ="ok";
		try {
			
			Map<String, Object> watchUser = new HashMap<String, Object>();
			WatchUser user = watchUserService.findOne("userOpenId",userOpenId);
			watchUser.put("openid",user.getUserOpenId());
			watchUser.put("headimgurl", user.getUserHeadImg());
			watchUser.put("sex", user.getUserSex());
			watchUser.put("city", user.getUserCity());
			watchUser.put("province",user.getUserProvince());
			watchUser.put("country", user.getUserCountry());
			watchUser.put("nickname", user.getUserNickName());
			Live live = liveService.find(liveId);
			if (null != live) {
				// 获取线路信息
				Line line = lineService.find(live.getMainid());
				// 获取机构信息中的appid，appsecret
				Organ weixin = organService.find(line.getOrganid());
				watchUser.put("appid", weixin.getAppId());
			//	watchUser.put("mchid",weixin.getAppSecret());
				watchUser.put("mchid",weixin.getMchid());
				session.setAttribute("apikey",weixin.getApikey());
			}
	 

			// 1.将用户信息以及直播id放入session中
			watchUser.put("liveId", liveId);
		
			session.setAttribute("watchUser", watchUser);
			map.put("statusCode", "200");
			 
		} catch (Exception e) {
			map.put("statusCode", "400");
		}
		map.put("result", result);
		return map; 
	}
}
